import redis
import time
from daili_ip import Daliip
class ProxyPool():
    def __init__(self):
        self.redis_conn = redis.StrictRedis(
            host='localhost',
            port = 6379,
            decode_responses=True
        )
        self.i = 0
        self.ip_s = Daliip().get_daili_ip()
        # if self.ip_s:
        #     if self.i<len(self.ip_s):
        #         self.ip_s = daili_ip.get_daili_ip()
        #         self.i = 0

    def set_proxy(self):
        proxy_odd = None
        while True:
            if self.i >= len(self.ip_s):
                Daliip().ipp_s = []
                self.ip_s = Daliip().get_daili_ip()
                self.i = 0
            proxy_new = self.ip_s[self.i]
            if proxy_new != proxy_odd:
                proxy_odd = proxy_new
                self.redis_conn.delete('proxy')
                self.redis_conn.sadd('proxy',proxy_new)
                self.i+=1
                print(proxy_new)
                time.sleep(2)
            else:
                time.sleep(1)
    def get_proxy(self):
        # print(self.ip_s)
        proxy_s = self.redis_conn.srandmember('proxy',1)
        # print(ret)
        if proxy_s:
            return proxy_s[0]
        else:
            time.sleep(0.1)
            return self.get_proxy()

if __name__ == '__main__':
    # ProxyPool().get_proxy()
    ProxyPool().set_proxy()

